package com.heima.leetcode.practice;

/**
 * @author 勾新杰
 * @version 1.0
 * @description: leetcode 235. 二叉搜索树的最近公共祖先
 * @date 2025/3/13 22:07
 */
public class E235 {

    /**
     * 递归解法
     * @param root root
     * @param p p
     * @param q q
     * @return 最近公共祖先
     */
    @SuppressWarnings("all")
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || root == p || root == q) return root;
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if (left != null && right != null) return root;
        else if(left != null) return left;
        else if(right != null) return right;
        else return null;
    }
}
